package com.mse.service.biz.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;

import com.mse.mapper.biz.MemberMapper;
import com.mse.model.biz.Member;
import com.mse.model.biz.MemberIllness;
import com.mse.service.biz.MemberIllnessService;
import com.mse.service.biz.MemberService;

import top.ibase4j.core.base.BaseServiceImpl;
import top.ibase4j.core.exception.BusinessException;
import top.ibase4j.core.support.Pagination;
import top.ibase4j.core.util.DataUtil;
import top.ibase4j.core.util.DateUtil;
import top.ibase4j.core.util.IDCardUtil;
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ShenHuaJie
 * @since 2019-04-05
 */
@Service
@CacheConfig(cacheNames = "TMember")
public class MemberServiceImpl extends BaseServiceImpl<Member, MemberMapper> implements MemberService {
    private MemberIllnessService illnessService;

    @Override
    public Member update(Member record) {
        if(DataUtil.isNotEmpty(record.getCardNo())) {
            try {
                record.setBirthDay(new Date(IDCardUtil.getBirthdayFromPersonIDCode(record.getCardNo()).getTime()));
            } catch (Throwable e) {
                throw new BusinessException("身份证号码错误");
            }
        }
        Member result = super.update(record);
        if (record.getNess() == null) {
            record.setNess(new MemberIllness());
        }
        illnessService.deleteByEntity(new MemberIllness().setMemberId(result.getId()));
        record.getNess().setMemberId(result.getId());
        record.getNess().setCreateBy(record.getCreateBy());
        record.getNess().setUpdateBy(record.getUpdateBy());
        illnessService.update(record.getNess());
        return result;
    }

    @Override
    public Pagination<Member> query(Map<String, Object> params) {
        if (DataUtil.isNotEmpty(params.get("minAge"))) {
            params.put("maxBirthDay", DateUtil.addDate(new Date(), Calendar.YEAR,
                -Integer.parseInt(params.get("minAge").toString())));
        }
        if (DataUtil.isNotEmpty(params.get("maxAge"))) {
            params.put("minBirthDay", DateUtil.addDate(new Date(), Calendar.YEAR,
                -Integer.parseInt(params.get("maxAge").toString())));
        }
        Pagination<Member> pagination = super.query(params);
        pagination.getRecords().parallelStream().forEach(member -> {
            member.setNess(illnessService.selectOne(new MemberIllness().setMemberId(member.getId())));
        });
        return pagination;
    }
}
